<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/26
 * Time: 2:25 PM
 */
namespace app\common\services;

use app\common\exceptions\BizException;
use app\common\models\CoreAttach;
use app\common\services\OssClient;
use app\common\services\QcloudCosClient;
use app\common\facades\Setting;

class Upload
{
    /**
     * 上传远程附件
     * @param $filename
     * @param $remote Setting:cms.remote_attach
     * @throws BizException
     * @throws \OSS\Core\OssException
     */
    public static function remote($filename,$remote){
        $type = $remote['type'];
        if (!$type) {
            throw new BizException('上传方式错误');
        }
        $remote = Setting::get('cms.remote_attach');
        if ($type == CoreAttach::UPLOAD_ALIOSS) {
            $ossClient = new OssClient($remote['alioss']['key'], $remote['alioss']['secret'], $remote['alioss']['endpoint']);
            $ossClient->uploadFile($remote['alioss']['bucket'], $filename, public_path() . '/static/upload/' . $filename);
        } elseif ($type == CoreAttach::UPLOAD_QCLOUDCOS) {
            $qcloudCosClient = (new QcloudCosClient(
                [
                    'region' => $remote['cos']['region'],
                    'schema' => 'https', //协议头部，默认为http
                    'credentials'=> array(
                        'secretId'  =>  $remote['cos']['secretid'],
                        'secretKey' => $remote['cos']['secretkey'])
                ]
            ));
            $qcloudCosClient->uploadFile($remote['cos']['bucket'],public_path() . '/static/upload/' . $filename,$filename);
        }
    }

    /**
     * 删除远程文件
     * @param $filename
     * @param $remote Setting:cms.remote_attach
     * @throws BizException
     * @throws \OSS\Core\OssException
     */
    public static function remoteDelete($filename,$remote){
        $type = $remote['type'];
        if (!$type) {
            throw new BizException('上传方式错误');
        }
        if ($type == CoreAttach::UPLOAD_ALIOSS) {
            $ossClient = new OssClient($remote['alioss']['key'], $remote['alioss']['secret'], $remote['alioss']['endpoint']);
            $ossClient->deleteObject($remote['alioss']['bucket'], $filename);
        } elseif ($type == CoreAttach::UPLOAD_QCLOUDCOS) {
            $qcloudCosClient = (new QcloudCosClient(
                [
                    'region' => $remote['cos']['region'],
                    'schema' => 'https', //协议头部，默认为http
                    'credentials'=> array(
                        'secretId'  =>  $remote['cos']['secretid'],
                        'secretKey' => $remote['cos']['secretkey'])
                ]
            ));
            $qcloudCosClient->deleteFile($remote['cos']['bucket'],$filename);
        }
    }
}